<template>
  <div
    @dragleave="dragOver = false"
    @dragover="dragOver = true"
    ref="uploadTag"
    class="uploadImg"
  >
    <div class="uploadImg-list">
      <div
        class="select-img-item"
        :class="[
          {
            'select-img-itemHidden': itemHidden,
            'transition-none': multiple == 1,
          },
        ]"
        :style="{
          width: width,
          height: height,
        }"
        v-for="(item, index) in selectImg"
        :key="index"
      >
        <!-- backgroundImage: `url(${item.base64})`, -->
        <img :src="item.base64" alt="" />
        <div class="operation">
          <!-- <span @click="onPreview(item)">预览</span> -->
          <span @click="delImg(index)">删除</span>
        </div>
        <div class="bg"></div>
      </div>
      <div
        :class="[
          'uploadImg-list-item',
          'transition-none',
          { 'drag-over': dragOver },
        ]"
        :style="{ width: width, height: height }"
        v-if="selectImg.length < multiple"
      >
        <div class="uploadImg-icon">
          <i class="el-icon-plus"></i>
          <p
            :style="{
              width: width,
            }"
          >
            {{ tips }}
          </p>
        </div>
        <input
          class="file"
          v-if="multiple <= 1"
          type="file"
          @change="onSelectImg"
          accept="image/*"
        />
        <input
          v-if="multiple > 1"
          class="file"
          multiple
          type="file"
          @change="onSelectImg"
          accept="image/*"
        />
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: "upload-img" + Math.random(),
  props: {
    multiple: {
      default: 8,
      type: Number,
    },
    tips: {
      default: "拖入/单击选择图片",
    },
    previewImg: {
      default() {
        return [];
      },
    },
    fixedNumber: {
      default() {
        return [6, 6];
      },
    },
    height: {
      default: "125px",
    },
    width: {
      default: "125px",
    },
  },
  components: {},
  data() {
    return {
      selectImg: [],
      currentImgNum: 0,
      cropperShow: false,
      editImgSrc: "",
      editImgIndex: null,
      editSrc: "",

      oldData: null, // 开始排序时按住的旧数据
      newData: null, // 拖拽过程的数据
      flag: true, //节流 防止跳动
      itemHidden: true,

      dragOver: false,
    };
  },

  mounted() {},
  watch: {
    previewImg: {
      deep: true,
      immediate: true,
      async handler() {
        this.initData();
      },
    },
  },
  methods: {
    initData() {
      let list = [];
      for (let item of this.previewImg) {
        let data = {};
        data.base64 = item.url;
        data.file = item.url;
        data.originUrl = item.url;
        list.push(data);
        data.id = Date.now();
        this.currentImgNum += 1;
      }
      this.selectImg = list;
      this.$emit("change", this.selectImg);
    },
    onSelectImg(data) {
      if (data.target.files.length <= 0) return;
      let imgNum = this.multiple - this.selectImg.length;
      let files = [...data.target.files];
      console.log(files, "files");

      files = files.slice(0, imgNum);

      files.forEach((file, index) => {
        if (window.FileReader) {
          let that = this;
          var reader = new FileReader();
          reader.readAsDataURL(file);
          //监听文件读取结束后事件
          reader.onloadend = function (e) {
            // 转blob格式
            let blobImg = that.dataURLtoBlob(reader.result);
            // 整理数据
            that.selectImg.push({
              base64: reader.result,
              blobImg: blobImg,
              file: file,
              id: Date.now() + "" + index,
            });
            that.$emit("change", that.selectImg);
          };
        }
      });
    },
    delImg(index) {
      this.selectImg.splice(index, 1);
      this.$emit("change", this.selectImg);
    },
    onPreview(item) {
      this.$emit("onPreview", {
        item: item,
        selectImg: this.selectImg,
      });
    },
    editImg(item, index) {
      this.editImgIndex = index;
      this.editImgSrc = item.base64;
      this.cropperShow = true;
      this.$emit("change", this.selectImg);
    },
    successImg(img) {
      this.editSrc = img.base64;
      this.selectImg[this.editImgIndex].base64 = img.base64;
      this.selectImg[this.editImgIndex].file = img.file;
      this.selectImg[this.editImgIndex].originUrl = "";
      this.editImgSrc = "";
      this.$emit("change", this.selectImg);
      this.cropperShow = false;
    },
    clearData() {
      this.selectImg = [];
      this.currentImgNum = 0;
    },
    // 转 blob格式
    dataURLtoBlob(dataurl) {
      var arr = dataurl.split(",");
      //注意base64的最后面中括号和引号是不转译的
      var _arr = arr[1].substring(0, arr[1].length - 2);
      var mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(_arr),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], {
        type: mime,
      });
    },
    // 转base64
    blobToDataURL(blob, callback) {
      let fileReade = new FileReader();
      fileReade.onload = function (e) {
        callback(e.target.result);
      };
      fileReade.readAsDataURL(blob);
    },
  },
};
</script>
<style lang="scss" scoped>
.uploadImg-list {
  display: flex;
  flex-wrap: wrap;
}
.transition-wrapper {
  display: flex;
  flex-wrap: wrap;
}
.uploadImg-list .uploadImg-list-item,
.uploadImg-list .select-img-item {
  width: 100px;
  height: 100px;
  border: 1px solid #d9d9d9;
  background: #fdfdfd;
  border-radius: 5px;
  position: relative;
  overflow: hidden;
  display: inline-block;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #ccc;
  margin-right: 10px;
  margin-bottom: 10px;
  transition: all 0.3s;
  background-size: cover;
}
.uploadImg-list .transition-none {
  transition: none !important;
}
.uploadImg-list .uploadImg-list-item {
  border: 1px dashed #d9d9d9 !important;
}
.uploadImg-list .uploadImg-list-item:hover {
  border: 1px dashed #409eff !important;
}
.uploadImg-list .drag-over {
  border: 1px dashed #409eff !important;
}

.uploadImg-list .uploadImg-list-item .uploadImg-icon {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}
.uploadImg-list .uploadImg-list-item i {
  font-size: 30px;
}
.uploadImg-list .uploadImg-list-item p {
  line-height: 26px;
  word-break: keep-all;
}
.uploadImg-list .uploadImg-list-item input {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  opacity: 0;
}

// 选中的图片列表
.uploadImg-list .select-img-item {
  cursor: move;
  overflow: hidden;
}

.uploadImg-list .select-img-item img {
  object-fit: contain;
  // position: absolute;
  // left: 50%;
  // top: 50%;
  // transform: translate(-50%, -50%);
}

// 操作
.uploadImg-list .select-img-item .operation {
  width: 100%;
  position: absolute;
  z-index: 2;
  cursor: pointer;
  user-select: none;
  text-align: center;
  // display: none;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
.uploadImg-list .select-img-item .operation span {
  margin: 0 5px;
  color: #fdfdfd;
}
.uploadImg-list .select-img-item .bg {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
  display: none;
}

// 蒙版 操作
.uploadImg-list .select-img-itemHidden:hover .operation {
  display: block !important;
}
.uploadImg-list .select-img-itemHidden:hover .bg {
  display: block !important;
}
</style>
